#include "gamewidget.h"
#include <QRandomGenerator>
#include <QApplication>
#include <QPainter>
#include <QKeyEvent>
#include <QPushButton>
#include <QVBoxLayout>
#include <QLabel>
#include <QPixmap>

GameWidget::GameWidget(QWidget *parent) : QWidget(parent) {
    setFocusPolicy(Qt::StrongFocus);
    setFixedSize(800, 600);

    // 加载背景图片
    backgroundImage = QPixmap(":/images/space_background.jpg");
    if (backgroundImage.isNull()) {
        // 如果资源加载失败，使用纯黑色背景
        backgroundImage = QPixmap(size());
        backgroundImage.fill(Qt::black);
    }

    // 创建开始界面控件
    startWidget = new QWidget(this);
    startWidget->setGeometry(0, 0, width(), height());

    QVBoxLayout *startLayout = new QVBoxLayout(startWidget);

    QLabel *titleLabel = new QLabel("星际飞机大战", startWidget);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("color: white; font-size: 48px; font-weight: bold;");
    startLayout->addWidget(titleLabel);

    QLabel *subtitleLabel = new QLabel("消灭敌机，保卫星际", startWidget);
    subtitleLabel->setAlignment(Qt::AlignCenter);
    subtitleLabel->setStyleSheet("color: #aaa; font-size: 24px;");
    startLayout->addWidget(subtitleLabel);

    startLayout->addSpacing(50);

    startButton = new QPushButton("开始游戏", startWidget);
    startButton->setStyleSheet("background-color: #4CAF50; color: white; font-size: 24px; padding: 15px 30px; border-radius: 8px;");
    startButton->setFixedSize(250, 60);
    connect(startButton, &QPushButton::clicked, this, &GameWidget::startGame);
    startLayout->addWidget(startButton, 0, Qt::AlignCenter);

    QPushButton *startExitButton = new QPushButton("退出游戏", startWidget);
    startExitButton->setStyleSheet("background-color: #F44336; color: white; font-size: 24px; padding: 15px 30px; border-radius: 8px;");
    startExitButton->setFixedSize(250, 60);
    connect(startExitButton, &QPushButton::clicked, this, &GameWidget::exitGame);
    startLayout->addWidget(startExitButton, 0, Qt::AlignCenter);

    startLayout->addStretch();

    QLabel *instructionsLabel = new QLabel("操作说明: A/D移动, 空格发射, Q退出", startWidget);
    instructionsLabel->setAlignment(Qt::AlignCenter);
    instructionsLabel->setStyleSheet("color: #ccc; font-size: 16px;");
    startLayout->addWidget(instructionsLabel);

    // 创建游戏结束界面控件
    gameOverWidget = new QWidget(this);
    gameOverWidget->setGeometry(0, 0, width(), height());
    gameOverWidget->setStyleSheet("background-color: rgba(0, 0, 0, 0.8);");
    gameOverWidget->hide();

    QVBoxLayout *layout = new QVBoxLayout(gameOverWidget);

    gameOverLabel = new QLabel("游戏结束！", gameOverWidget);
    gameOverLabel->setAlignment(Qt::AlignCenter);
    gameOverLabel->setStyleSheet("color: red; font-size: 36px; font-weight: bold;");
    layout->addWidget(gameOverLabel);

    scoreLabel = new QLabel("你的得分：0", gameOverWidget);
    scoreLabel->setAlignment(Qt::AlignCenter);
    scoreLabel->setStyleSheet("color: white; font-size: 24px;");
    layout->addWidget(scoreLabel);

    restartButton = new QPushButton("重新开始", gameOverWidget);
    restartButton->setStyleSheet("background-color: green; color: white; font-size: 20px; padding: 10px; border-radius: 5px;");
    restartButton->setFixedSize(200, 50);
    connect(restartButton, &QPushButton::clicked, this, &GameWidget::restartGame);
    layout->addWidget(restartButton, 0, Qt::AlignCenter);

    QPushButton *gameOverExitButton = new QPushButton("退出游戏", gameOverWidget);
    gameOverExitButton->setStyleSheet("background-color: red; color: white; font-size: 20px; padding: 10px; border-radius: 5px;");
    gameOverExitButton->setFixedSize(200, 50);
    connect(gameOverExitButton, &QPushButton::clicked, this, &GameWidget::exitGame);
    layout->addWidget(gameOverExitButton, 0, Qt::AlignCenter);

    layout->setSpacing(30);
    layout->setAlignment(Qt::AlignCenter);

    gameTimer = new QTimer(this);
    connect(gameTimer, &QTimer::timeout, this, &GameWidget::updateGame);

    // 显示开始界面
    showStartScreen();
}

void GameWidget::showStartScreen() {
    // 初始化游戏状态
    gameOver = false;
    score = 0;
    bullets.clear();
    enemies.clear();

    // 显示开始界面
    startWidget->show();
    gameOverWidget->hide();

    // 停止游戏定时器
    gameTimer->stop();
}

void GameWidget::startGame() {
    resetGame();
    startWidget->hide();
    gameTimer->start(50); // 启动定时器
    setFocus(); // 确保获得焦点
}

void GameWidget::resetGame() {
    playerX = width() / 2;
    bullets.clear();
    enemies.clear();
    score = 0;
    gameOver = false;
    gameOverWidget->hide();
    update();
}

// 绘制玩家飞机
void GameWidget::drawPlayer(QPainter &painter, int x, int y) {
    painter.setBrush(Qt::green);

    // 绘制飞机主体
    QPolygon body;
    body.append(QPoint(x, y + 30));       // 底部中点
    body.append(QPoint(x - 15, y + 15));   // 左下
    body.append(QPoint(x - 10, y));        // 左中
    body.append(QPoint(x, y - 10));        // 顶部
    body.append(QPoint(x + 10, y));        // 右中
    body.append(QPoint(x + 15, y + 15));   // 右下
    painter.drawPolygon(body);

    // 绘制机翼
    painter.drawRect(x - 15, y + 15, 30, 5);
}

// 绘制敌机
void GameWidget::drawEnemy(QPainter &painter, int x, int y) {
    painter.setBrush(Qt::red);

    // 绘制敌机主体
    QPolygon body;
    body.append(QPoint(x, y));            // 顶部中点
    body.append(QPoint(x - 15, y + 15));   // 左上
    body.append(QPoint(x - 10, y + 30));   // 左下
    body.append(QPoint(x, y + 20));        // 底部
    body.append(QPoint(x + 10, y + 30));   // 右下
    body.append(QPoint(x + 15, y + 15));   // 右上
    painter.drawPolygon(body);

    // 绘制机翼
    painter.drawRect(x - 15, y + 15, 30, 5);
}

void GameWidget::paintEvent(QPaintEvent *) {
    QPainter painter(this);

    // 绘制背景
    painter.drawPixmap(0, 0, width(), height(), backgroundImage);

    if (gameOver || startWidget->isVisible()) return;

    // 绘制玩家飞机
    drawPlayer(painter, playerX + 15, height() - 50);

    // 绘制子弹（简化为矩形）
    painter.setBrush(Qt::yellow);
    for (auto &b : bullets) {
        if (b.active) painter.drawRect(b.x, b.y, 5, 10);
    }

    // 绘制敌机
    painter.setBrush(Qt::red);
    for (auto &e : enemies) {
        if (e.active) {
            drawEnemy(painter, e.x + 15, e.y);
        }
    }

    // 显示分数
    painter.setPen(Qt::white);
    painter.drawText(10, 20, QString("得分: %1").arg(score));
}

void GameWidget::keyPressEvent(QKeyEvent *event) {
    if (startWidget->isVisible()) {
        if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
            startGame();
        } else if (event->key() == Qt::Key_Q) {
            exitGame();
        }
        return;
    }

    if (gameOver) {
        if (event->key() == Qt::Key_R) {
            restartGame();
        } else if (event->key() == Qt::Key_Q) {
            exitGame();
        }
        return;
    }

    switch (event->key()) {
        case Qt::Key_A:
            playerX = qMax(0, playerX - 20);
            break;
        case Qt::Key_D:
            playerX = qMin(width() - 30, playerX + 20); // 30为玩家宽度
            break;
        case Qt::Key_Space:
            bullets.push_back({playerX + 15, height() - 60, true});
            break;
        case Qt::Key_Q:
            showStartScreen();
            break;
    }
    update(); // 触发重绘
}

void GameWidget::updateGame() {
    if (gameOver) return;

    // 随机生成敌机
    if (QRandomGenerator::global()->bounded(100) < 5) { // 5% 的概率生成敌机
        int x = QRandomGenerator::global()->bounded(width() - 30); // 随机位置
        enemies.push_back({x, 0, 0, true});
    }

    // 移动子弹
    for (auto &b : bullets) {
        if (b.active) {
            b.y -= 10; // 子弹向上移动
            if (b.y < 0) {
                b.active = false; // 子弹超出屏幕，标记为不活跃
            }
        }
    }

    // 移动敌机
    for (auto &e : enemies) {
        if (e.active) {
            e.y += 5; // 敌机向下移动
            if (e.y > height()) {
                e.active = false; // 敌机超出屏幕，标记为不活跃
                score++; // 躲避敌机，增加分数
            }
        }
    }

    // 碰撞检测：子弹与敌机
    for (auto &b : bullets) {
        if (b.active) {
            for (auto &e : enemies) {
                if (e.active) {
                    if (b.x >= e.x && b.x <= e.x + 30 && b.y >= e.y && b.y <= e.y + 30) {
                        // 子弹和敌机碰撞
                        b.active = false;
                        e.active = false;
                        score += 5; // 增加5分
                    }
                }
            }
        }
    }

    // 碰撞检测：玩家与敌机
    for (auto &e : enemies) {
        if (e.active) {
            // 玩家飞机的位置和大小
            int playerLeft = playerX;
            int playerRight = playerX + 30;
            int playerTop = height() - 50;
            int playerBottom = height() - 20;

            // 敌机的位置和大小
            int enemyLeft = e.x;
            int enemyRight = e.x + 30;
            int enemyTop = e.y;
            int enemyBottom = e.y + 30;

            // 检测碰撞
            if (playerLeft < enemyRight &&
                playerRight > enemyLeft &&
                playerTop < enemyBottom &&
                playerBottom > enemyTop) {
                endGame();
                return;
            }
        }
    }

    // 移除不活跃的子弹和敌机
    auto newEndBullets = std::remove_if(bullets.begin(), bullets.end(), [](const Bullet &b) { return !b.active; });
    bullets.erase(newEndBullets, bullets.end());

    auto newEndEnemies = std::remove_if(enemies.begin(), enemies.end(), [](const Enemy &e) { return !e.active; });
    enemies.erase(newEndEnemies, enemies.end());

    update(); // 触发重绘
}

void GameWidget::endGame() {
    gameOver = true;
    gameTimer->stop();

    // 更新分数显示
    scoreLabel->setText(QString("你的得分：%1").arg(score));

    // 显示游戏结束界面
    gameOverWidget->show();
}

void GameWidget::restartGame() {
    resetGame();
    startWidget->hide();
    gameTimer->start(50);
}

void GameWidget::exitGame() {
    QApplication::quit();
}
